<template>
    <div>
        <!-- <el-divider></el-divider> -->
        <el-form :rules="rules"  label-width="100px" style="width: 900px;" :model="movieAddList" ref="movieList">
            <el-form-item label="封面图片" prop="cover">
                <el-upload
                    class="avatar-uploader"
                    :action="`${$UPLOADURL}/upload`"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="movieAddList.cover" :src="movieAddList.cover" class="avatar" style="object-fit:contain">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="电影类别" >
                <template>
                    <el-radio v-model="movieAddList.category_id" :label="1">热映</el-radio>
                    <el-radio v-model="movieAddList.category_id" :label="2">待映</el-radio>
                    <el-radio v-model="movieAddList.category_id" :label="3">经典</el-radio>
                </template>
            </el-form-item>
            <el-form-item label="电影名称" prop="title">
                <el-input v-model="movieAddList.title"></el-input>
            </el-form-item>
            <el-form-item label="电影类型" prop="type">
                <el-select v-model="movieAddList.type" multiple placeholder="请选择电影类型" style="width: 100%;">
                      <el-option v-for="item in movieTypeItems" :key="item.id" :label="item.typename" :value="item.typename"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="电影主演" prop="star_actor">
                <template>
                    <el-select
                        style="width: 100%;"
                        v-model="movieAddList.star_actor"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入演员"
                        :remote-method="remoteMethod"
                        :loading="loading">
                        <el-option v-for="items in actorsNameList" :key="items.id" :label="items.actor_name" :value="items.actor_name"></el-option>
                    </el-select>
                </template>
            </el-form-item>
            <el-form-item label="上映时间" prop="showingon">
                <el-date-picker
                    value-format="yyyy-MM-DD"
                    v-model="movieAddList.showingon"
                    type="date"
                    placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="电影评分" prop="score">
                <el-rate
                    :max="10"
                    v-model="movieAddList.score"
                    :colors="colors"
                   
                    >
                </el-rate>
            </el-form-item>
            <el-form-item label="电影时长" prop="duration">
                <el-input v-model="movieAddList.duration" placeholder="输入电影时长(单位是分钟)"></el-input>
            </el-form-item>
            <el-form-item label="电影简介" prop="description">
                <div style="border: 1px solid #ccc;">
                    <Toolbar
                        style="border-bottom: 1px solid #ccc"
                        :editor="editor"
                        :defaultConfig="toolbarConfig"
                        :mode="mode"
                    />
                    <Editor
                        style="height: 500px; overflow-y: hidden;"
                        v-model="movieAddList.description"
                        :defaultConfig="editorConfig"
                        :mode="mode"
                        @onCreated="onCreated"
                    />
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addMovieBtn">立即更新电影信息</el-button>
                <el-button>取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import httpApi from '../../http';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { DomEditor } from '@wangeditor/editor'
    export default {
        components: { Editor, Toolbar },
        data() {
            return {
                movieAddList:{
                    id:this.$route.params.id,  //修改电影的电影id
                    // 图片
                    cover:'',
                    category_id:1,
                    title:'',
                    type:[],
                    star_actor:[],
                    showingon:'',
                    score:0,
                    description:'',
                    duration:'',
                },
                rules:{
                    cover:[
                         { required: true, message: '电影图片不能为空', trigger: 'blur' },
                    ],
                    title:[
                        { required: true, message: '电影名称不能为空', trigger: 'blur' },
                    ],
                    categoryId:[
                    { required: true, message: '电影类型不能为空', trigger: 'change' },
                    ],
                    score:[
                    { required: true, message: '电影评分不能为空', trigger: 'change' },
                    ],
                    type:[
                        { required: true, message: '电影类型必填', trigger: 'change' },
                    ],
                    star_actor:[
                        { required: true, message: '电影主演不能为空', trigger: 'change' },
                    ],
                    showingon:[
                        { required: true, message: '发表时间必填', trigger: 'blur' },
                    ],
                    duration:[
                        { required: true, message: '请输入活动名称', trigger: 'blur' },
                    ],
                    description:[
                        { required: true, message: '请填写电影时长 ', trigger: 'blur' },
                    ],
                },
                colors:['#99A9BF', '#F7BA2A', '#FF9900'],
                movieTypeItems:'',
                loading: false,
                actorsNameList:'',  //用于保持搜索演员结果
                // editor组件变量
                editor: null,
                html: '<p>hello</p>',
                // 工具栏可见按钮配置
                toolbarConfig: { 
                    toolbarKeys:['header1','header2','header3','bold','|',
                    {iconSvg: 
                        "<svg viewBox=\"0 0 1024 1024\"><path d=\"M959.877 128l0.123 0.123v767.775l-0.123 0.122H64.102l-0.122-0.122V128.123l0.122-0.123h895.775zM960 64H64C28.795 64 0 92.795 0 128v768c0 35.205 28.795 64 64 64h896c35.205 0 64-28.795 64-64V128c0-35.205-28.795-64-64-64zM832 288.01c0 53.023-42.988 96.01-96.01 96.01s-96.01-42.987-96.01-96.01S682.967 192 735.99 192 832 234.988 832 288.01zM896 832H128V704l224.01-384 256 320h64l224.01-192z\"></path></svg>",
                        key: "group-image",
                        menuKeys:['insertImage', 'uploadImage'],
                        title: "图片",
                    },
                    'color',
                    ],
                    },
                editorConfig: { 
                    placeholder: '请输入内容...',
                    MENU_CONF:{
                        uploadImage:{
                            fieldName:'file', //定义上传文件的字段
                            server:this.$UPLOADURL+'/upload', //上传图片的路径
                            maxFileSize: 1 * 1024 * 1024, // 1M
                            allowedFileTypes: ['image/*'], //允许文件上传的类型
                            // 自定义插入图片  res上传后返回的响应   insertFunc: 需要调用该回调方法才能插入图片
                            customInsert(res, insertFn) {  // TS 语法
                            // customInsert(res, insertFn) {                  // JS 语法
                            // res 即服务端的返回结果
                                console.log('上传成功后的反馈',res)
                            // 从 res 中找到 url alt href ，然后插入图片
                            insertFn(res.data)
                        },
                    },
                },
            },
                mode: 'default', // or 'simple'        
            }
        },
        methods:{
            // 获取电影信息回填表单
            queryMovieData(){
                let id = this.$route.params
                httpApi.movieApi.queryMovie(id).then(res=>{
                    console.log('当前电影信息',res)
                    this.movieAddList = res.data.data
                    this.movieAddList.type = this.movieAddList.type.split("/")
                    this.movieAddList.star_actor = this.movieAddList.star_actor.split("/")
                    this.movieAddList.score = parseFloat(this.movieAddList.score)
                    delete this.movieAddList.actorApi
                    delete this.movieAddList.director
                    delete this.movieAddList.thumb
                })
            },
            // 图片上传后的操作i
            handleAvatarSuccess(res,file){
                console.log(res)
                this.movieAddList.cover = res.data
                // 移除错误验证消息
                this.$refs['movieList'].clearValidate('cover')            
            },
            // 图片上传前验证图片大小
            beforeAvatarUpload(file){
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            // 提交修改电影表单按钮
            addMovieBtn(){
                this.movieAddList.star_actor = this.movieAddList.star_actor.join('/');
                this.movieAddList.type = this.movieAddList.type.join('/');
                console.log(this.movieAddList)
                this.$refs['movieList'].validate((valid) => {
                    if (valid) {
                        httpApi.movieApi.updateMovie(this.movieAddList).then(res=>{
                                if(res.data.code==200){
                                            this.$message({
                                            message: '修改电影成功',
                                            type: 'success'
                                            });
                                    //重置表单
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                })
            },
            // 电影类型请求
            MovieType(){
                httpApi.movieApi.MovieType().then(res=>{
                    console.log(res);
                    this.movieTypeItems = res.data.data
                })
            },
            // 查询演员方法  当搜索框内容改变触发
            remoteMethod(query){
                console.log(query)
                let params = {name:query}
                httpApi.actorApi.queryActorsByName(params).then(res=>{
                    console.log(res)
                    this.actorsNameList = res.data.data
                })
            },
            // editor组件方法
            onCreated(editor) {
                this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
                //获取工具栏对象
                // setTimeout(()=>{
                //     const toolbar = DomEditor.getToolbar(this.editor)
                //     const curToolbarConfig = toolbar.getConfig()
                //     console.log(curToolbarConfig.toolbarKeys) // 当前菜单排序和分组
                // },2000)
            },
        },
        mounted() {
            this.MovieType()
            // 模拟 ajax 请求，异步渲染编辑器
            setTimeout(() => {
                this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
            }, 1500)

            this.queryMovieData()

        },
        beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
    }
</script>

<style lang="scss" scoped>

</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
  </style>
  <style>
.el-rate {
    margin-top: 10px;
}</style>